import appApi from '@/sheep/api/app';
import { defineStore } from 'pinia';
import $platform from '@/sheep/platform';
import $router from '@/sheep/router';
import user from './user';
import socket from './socket';
import sys from './sys';
import { baseUrl } from '@/sheep/config';
// #ifdef APP-PLUS
const TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
const TUICallKitEvent = uni.requireNativePlugin('globalEvent');

// #endif
const app = defineStore({
  id: 'app',
  state: () => ({
    info: {
      // 应用信息
      name: '', // 商城名称
      logo: '', // logo
      version: '', // 版本号
      cdnurl: '', // 云存储域名
      filesystem: '', // 云存储平台
      user_protocol: {}, // 用户协议
      privacy_protocol: {}, // 隐私协议
      about_us: {}, // 关于我们
      copyright: '', // 版权信息 I
      copytime: '', // 版权信息 II
    },
    platform: {
      payment: [], // 支持的支付方式
      share: {
        methods: [], // 支持的分享方式
        forwardInfo: {}, // 默认转发信息
        posterInfo: {}, // 海报信息
        linkAddress: '', // 复制链接地址
      },
      auto_login: 0, // 自动登陆
      bind_mobile: 0, // 登陆后绑定手机号提醒 (弱提醒，可手动关闭)
    },
    chat: {},
    tabber: {
      mode: 1,
      layout: 1,
      inactiveColor: '#8C8C8C',
      activeColor: '#dfbe68',
      list: [
        {
          inactiveIcon: '/static/home.png',
          activeIcon: '/static/home.png',
          url: '/pages/index/index',
          text: '首页',
        },
        {
          inactiveIcon: '/static/sc.png',
          activeIcon: '/static/sc.png',
          url: '/pages/index/category?id=1',
          text: '商城',
        },
        {
          inactiveIcon: '/static/zb.png',
          activeIcon: '/static/zb.png',
          url: '/pages/index/video',
          text: '视频',
        },
        {
          inactiveIcon: '/static/hy.png',
          activeIcon: '/static/hy.png',
          url: '/pages/chat/content',
          text: '好友1',
        },
        {
          inactiveIcon: '/static/wd.png',
          activeIcon: '/static/wd.png',
          url: '/pages/index/user',
          text: '我的',
        },
      ],
      background: {
        type: 'color',
        bgImage: '',
        bgColor: '#FFFFFF',
      },
    },
    template: {
      // 店铺装修模板
      basic: {}, // 基本信息
      home: {
        // 首页模板
        style: {},
        data: [],
      },
      user: {
        // 个人中心模板
        style: {},
        data: [],
      },
    },
    shareInfo: {}, // 全局分享信息
    has_wechat_trade_managed: 0, // 小程序发货信息管理  0 没有 || 1 有
  }),
  actions: {
    // 获取Shopro应用配置和模板
    async init(templateId = null) {
      //检查网络
      const networkStatus = await $platform.checkNetwork();
      if (!networkStatus) {
        $router.error('NetworkError');
      }

      // 检查配置
      if (typeof baseUrl === 'undefined') {
        $router.error('EnvError');
      }
      // #ifdef APP-PLUS
      TUICallKitEvent.addEventListener('onKickedOffline', (res) => {
        let userst = user();
        userst.logout();
      });
      TUICallKitEvent.addEventListener('onCallEnd', ({ roomID, callRole, totalTime }) => {
        let socketobj = socket();
        console.log('通话结束', roomID, callRole, totalTime);
        if (roomID) {
          if (callRole === 1) {
            socketobj.sendgroupapi({
              id: roomID,
              message: JSON.stringify({
                time: totalTime,
              }),
              message_type: 'voice',
            });
          }
        }
      });
      // #endif

      const res = await appApi.init();
      if (res.code === 1) {
        this.info = res.data.app;
        this.platform = res.data.platform;
        this.template = res.data.template;

        this.has_wechat_trade_managed = res.data.has_wechat_trade_managed;
        if (!res.data.template) {
          $router.error('TemplateError');
        }
        this.chat = res.data.chat;

        // 加载主题
        const sysStore = sys();
        sysStore.setTheme();

        // 模拟用户登录
        const userStore = user();
        if (userStore.isLogin) {
          userStore.loginAfter();
        }
        const res1 = await appApi.app();

        if (res1.code === 1) {
          this.homedata = res1.data;
          console.log(this.homedata, '==================');
          let isreset = true;
          if (/.apk/.test(this.homedata.app_file)) {
            isreset = false;
          }

          // #ifdef APP-PLUS

          plus.runtime.getProperty(plus.runtime.appid, (info) => {
            var version1 = info.version;

            console.log(this.homedata.app_version);
            if (version1 !== this.homedata.app_version) {
              console.log(version1);
              if (import.meta.env.SHOPRO_DEV === '1') {
                return;
              }

              // uni.showLoading({
              // 	title: '更新中....',
              // 	mask: true
              // });

              // #ifdef APP-PLUS

              let DownloadTask = uni.downloadFile({
                //执行下载
                url: this.homedata.app_file, //下载地址

                success: (downloadResult) => {
                  //下载成功

                  uni.hideLoading();
                  if (downloadResult.statusCode == 200) {
                    if (true) {
                      plus.runtime.install(
                        //安装//
                        downloadResult.tempFilePath,
                        {
                          force: true,
                        },
                        function (res) {
                          // utils.showToast('更新成功，重启中');
                          if (!isreset) {
                            return;
                          }
                          plus.runtime.restart();
                        },
                        function (res) {
                          // utils.showToast('更新成功，重启中');
                          sheep.$helper.toast(res);
                        },
                      );
                    }
                  }
                },
                fail(err) {
                  console.log(err);
                },
              });
              DownloadTask.onProgressUpdate((res) => {
                if (res.progress === 100) {
                  uni.hideLoading();
                  return;
                }
                uni.$u.throttle(() => {
                  uni.showLoading({
                    title: `更新中....(${res.progress}%)`,
                    mask: true,
                  });
                }, 2000);
              });
              // #endif
            }
          });

          // #endif
        }

        return Promise.resolve(true);
      } else {
        $router.error('InitError', res.msg || '加载失败');
      }
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'app-store',
      },
    ],
  },
});

export default app;
